import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

/// 应用生命周期状态枚举
enum AppState {
  /// 应用在前台且活跃，用户可以与应用交互
  foreground,
  
  /// 应用在前台但不活跃（例如来电话、通知下拉时）
  inactive,
  
  /// 应用在后台，不可见
  background,
  
  /// 应用正在被系统终止
  detached,
}

/// 生命周期回调函数类型定义
typedef AppLifecycleCallback = void Function(AppState state);
typedef AppStateChangeCallback = void Function(AppState oldState, AppState newState);

/// Flutter应用生命周期管理器
/// 
/// 提供应用前台/后台状态监听、回调注册等功能
/// 使用WidgetsBindingObserver监听系统级生命周期变化
class AppLifecycleManager extends GetxService with WidgetsBindingObserver {
  static const String tag = 'AppLifecycleManager';
  
  // 单例实例
  static AppLifecycleManager? _instance;
  static AppLifecycleManager get instance => _instance ??= AppLifecycleManager._();
  
  // 私有构造函数
  AppLifecycleManager._();
  
  /// 当前应用状态
  var currentState = AppState.foreground.obs;
  
  /// 上一次的应用状态
  AppState _previousState = AppState.foreground;
  
  /// 应用是否在前台
  bool get isInForeground => currentState.value == AppState.foreground;
  
  /// 应用是否在后台
  bool get isInBackground => currentState.value == AppState.background;
  
  /// 应用是否处于活跃状态
  bool get isActive => currentState.value == AppState.foreground;
  
  /// 应用进入后台的时间
  DateTime? _backgroundTime;
  
  /// 应用回到前台的时间
  DateTime? _foregroundTime;
  
  /// 后台持续时间（毫秒）
  int get backgroundDuration {
    if (_backgroundTime == null || isInForeground) return 0;
    return DateTime.now().difference(_backgroundTime!).inMilliseconds;
  }
  
  /// 前台持续时间（毫秒）
  int get foregroundDuration {
    if (_foregroundTime == null || isInBackground) return 0;
    return DateTime.now().difference(_foregroundTime!).inMilliseconds;
  }
  
  // 回调函数列表
  final List<AppLifecycleCallback> _lifecycleCallbacks = [];
  final List<AppStateChangeCallback> _stateChangeCallbacks = [];
  final List<VoidCallback> _foregroundCallbacks = [];
  final List<VoidCallback> _backgroundCallbacks = [];
  final List<VoidCallback> _inactiveCallbacks = [];
  final List<VoidCallback> _detachedCallbacks = [];
  
  /// 初始化生命周期管理器
  @override
  void onInit() {
    super.onInit();
    debugPrint('$tag: 初始化应用生命周期管理器');
    
    // 注册生命周期观察者
    WidgetsBinding.instance.addObserver(this);
    
    // 设置初始状态
    _foregroundTime = DateTime.now();
    
    debugPrint('$tag: 生命周期管理器初始化完成');
  }
  
  /// 销毁时清理资源
  @override
  void onClose() {
    debugPrint('$tag: 清理生命周期管理器资源');
    
    // 移除观察者
    WidgetsBinding.instance.removeObserver(this);
    
    // 清理回调列表
    _lifecycleCallbacks.clear();
    _stateChangeCallbacks.clear();
    _foregroundCallbacks.clear();
    _backgroundCallbacks.clear();
    _inactiveCallbacks.clear();
    _detachedCallbacks.clear();
    
    super.onClose();
  }
  
  /// 监听应用生命周期状态变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    
    AppState newAppState = _mapLifecycleState(state);
    _previousState = currentState.value;
    
    debugPrint('$tag: 应用状态变化 ${_previousState.name} → ${newAppState.name}');
    
    // 更新状态
    currentState.value = newAppState;
    
    // 记录时间戳
    _recordStateTimestamp(newAppState);
    
    // 触发回调
    _triggerCallbacks(newAppState);
    
    // 触发状态变化回调
    _triggerStateChangeCallbacks(_previousState, newAppState);
    
    // 调试信息
    if (kDebugMode) {
      _printStateInfo(newAppState);
    }
  }
  
  /// 映射系统生命周期状态到自定义状态
  AppState _mapLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        return AppState.foreground;
      case AppLifecycleState.inactive:
        return AppState.inactive;
      case AppLifecycleState.paused:
        return AppState.background;
      case AppLifecycleState.detached:
        return AppState.detached;
      default:
        return AppState.foreground;
    }
  }
  
  /// 记录状态变化时间戳
  void _recordStateTimestamp(AppState state) {
    final now = DateTime.now();
    switch (state) {
      case AppState.foreground:
        _foregroundTime = now;
        break;
      case AppState.background:
        _backgroundTime = now;
        break;
      case AppState.inactive:
      case AppState.detached:
        break;
    }
  }
  
  /// 触发相应的回调函数
  void _triggerCallbacks(AppState state) {
    // 触发通用生命周期回调
    for (final callback in _lifecycleCallbacks) {
      try {
        callback(state);
      } catch (e) {
        debugPrint('$tag: 生命周期回调执行错误: $e');
      }
    }
    
    // 触发特定状态回调
    List<VoidCallback> specificCallbacks;
    switch (state) {
      case AppState.foreground:
        specificCallbacks = _foregroundCallbacks;
        break;
      case AppState.background:
        specificCallbacks = _backgroundCallbacks;
        break;
      case AppState.inactive:
        specificCallbacks = _inactiveCallbacks;
        break;
      case AppState.detached:
        specificCallbacks = _detachedCallbacks;
        break;
    }
    
    for (final callback in specificCallbacks) {
      try {
        callback();
      } catch (e) {
        debugPrint('$tag: ${state.name}回调执行错误: $e');
      }
    }
  }
  
  /// 触发状态变化回调
  void _triggerStateChangeCallbacks(AppState oldState, AppState newState) {
    for (final callback in _stateChangeCallbacks) {
      try {
        callback(oldState, newState);
      } catch (e) {
        debugPrint('$tag: 状态变化回调执行错误: $e');
      }
    }
  }
  
  /// 打印状态信息（调试用）
  void _printStateInfo(AppState state) {
    final info = {
      'state': state.name,
      'isInForeground': isInForeground,
      'isInBackground': isInBackground,
      'backgroundDuration': backgroundDuration,
      'foregroundDuration': foregroundDuration,
      'timestamp': DateTime.now().toIso8601String(),
    };
    debugPrint('$tag: 状态信息 - $info');
  }
  
  // ==================== 公共API ====================
  
  /// 注册生命周期回调
  void addLifecycleCallback(AppLifecycleCallback callback) {
    if (!_lifecycleCallbacks.contains(callback)) {
      _lifecycleCallbacks.add(callback);
      debugPrint('$tag: 注册生命周期回调，当前回调数量: ${_lifecycleCallbacks.length}');
    }
  }
  
  /// 移除生命周期回调
  void removeLifecycleCallback(AppLifecycleCallback callback) {
    _lifecycleCallbacks.remove(callback);
    debugPrint('$tag: 移除生命周期回调，当前回调数量: ${_lifecycleCallbacks.length}');
  }
  
  /// 注册状态变化回调
  void addStateChangeCallback(AppStateChangeCallback callback) {
    if (!_stateChangeCallbacks.contains(callback)) {
      _stateChangeCallbacks.add(callback);
      debugPrint('$tag: 注册状态变化回调，当前回调数量: ${_stateChangeCallbacks.length}');
    }
  }
  
  /// 移除状态变化回调
  void removeStateChangeCallback(AppStateChangeCallback callback) {
    _stateChangeCallbacks.remove(callback);
    debugPrint('$tag: 移除状态变化回调，当前回调数量: ${_stateChangeCallbacks.length}');
  }
  
  /// 注册前台回调
  void addForegroundCallback(VoidCallback callback) {
    if (!_foregroundCallbacks.contains(callback)) {
      _foregroundCallbacks.add(callback);
      debugPrint('$tag: 注册前台回调，当前回调数量: ${_foregroundCallbacks.length}');
    }
  }
  
  /// 移除前台回调
  void removeForegroundCallback(VoidCallback callback) {
    _foregroundCallbacks.remove(callback);
    debugPrint('$tag: 移除前台回调，当前回调数量: ${_foregroundCallbacks.length}');
  }
  
  /// 注册后台回调
  void addBackgroundCallback(VoidCallback callback) {
    if (!_backgroundCallbacks.contains(callback)) {
      _backgroundCallbacks.add(callback);
      debugPrint('$tag: 注册后台回调，当前回调数量: ${_backgroundCallbacks.length}');
    }
  }
  
  /// 移除后台回调
  void removeBackgroundCallback(VoidCallback callback) {
    _backgroundCallbacks.remove(callback);
    debugPrint('$tag: 移除后台回调，当前回调数量: ${_backgroundCallbacks.length}');
  }
  
  /// 注册非活跃状态回调
  void addInactiveCallback(VoidCallback callback) {
    if (!_inactiveCallbacks.contains(callback)) {
      _inactiveCallbacks.add(callback);
    }
  }
  
  /// 移除非活跃状态回调
  void removeInactiveCallback(VoidCallback callback) {
    _inactiveCallbacks.remove(callback);
  }
  
  /// 注册应用销毁回调
  void addDetachedCallback(VoidCallback callback) {
    if (!_detachedCallbacks.contains(callback)) {
      _detachedCallbacks.add(callback);
    }
  }
  
  /// 移除应用销毁回调
  void removeDetachedCallback(VoidCallback callback) {
    _detachedCallbacks.remove(callback);
  }
  
  /// 获取当前状态信息
  Map<String, dynamic> getStateInfo() {
    return {
      'currentState': currentState.value.name,
      'isInForeground': isInForeground,
      'isInBackground': isInBackground,
      'isActive': isActive,
      'backgroundDuration': backgroundDuration,
      'foregroundDuration': foregroundDuration,
      'backgroundTime': _backgroundTime?.toIso8601String(),
      'foregroundTime': _foregroundTime?.toIso8601String(),
      'callbackCounts': {
        'lifecycle': _lifecycleCallbacks.length,
        'stateChange': _stateChangeCallbacks.length,
        'foreground': _foregroundCallbacks.length,
        'background': _backgroundCallbacks.length,
        'inactive': _inactiveCallbacks.length,
        'detached': _detachedCallbacks.length,
      },
    };
  }
  
  /// 清除所有回调
  void clearAllCallbacks() {
    debugPrint('$tag: 清除所有回调函数');
    _lifecycleCallbacks.clear();
    _stateChangeCallbacks.clear();
    _foregroundCallbacks.clear();
    _backgroundCallbacks.clear();
    _inactiveCallbacks.clear();
    _detachedCallbacks.clear();
  }
}
